<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>我的商品 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section>
        <h2>我的商品</h2>

        <div class="controls">
            <a th:href="@{/publish-product}" class="btn secondary">发布新商品</a>
        </div>

        <div class="card">
            <div id="productList"></div>
        </div>

        <div id="pagination" class="pagination"></div>
        <div id="msg"></div>
    </section>
</div>
<script>
    let page = 0, size = 10;

    async function loadMyProducts() {
        try {
            const res = await fetch(`/api/products/my?page=${page}&size=${size}`, {
                credentials: 'include'
            });

            // 检查是否需要登录
            if (res.status === 403 || res.status === 401) {
                window.location.href = '/login';
                return;
            }

            const data = await res.json();

            if (!data.content || data.content.length === 0) {
                document.getElementById('productList').innerHTML =
                    '<div class="empty-state">' +
                    '<p>您还没有发布任何商品</p>' +
                    '<a href="/publish-product" class="btn">立即发布</a>' +
                    '</div>';
                document.getElementById('pagination').innerHTML = '';
                return;
            }

            // 列表视图
            let listHtml = '<table>' +
                '<tr><th>商品图片</th><th>商品名称</th><th>价格</th><th>分类</th><th>状态</th><th>发布日期</th><th>有效期至</th><th>操作</th></tr>';

            for (const p of data.content) {
                // 格式化状态显示
                const statusMap = {
                    'pending': '待审核',
                    'on_sale': '上架中',
                    'off_sale': '已下架',
                    'sold': '已售出',
                    'sold_out': '已售罄'
                };
                const status = statusMap[p.status] || p.status;

                // 格式化日期
                const createdDate = new Date(p.createdAt).toLocaleString();
                const validUntil = p.validUntil ? new Date(p.validUntil).toLocaleString() : '永久有效';

                // 商品分类
                const category = p.category ? p.category.name : '未分类';

                // 操作按钮
                const editBtn = `<a href="/edit-product?id=${p.id}" class="btn">编辑</a>`;
                let statusBtn = '';

                // 根据商品状态显示不同的按钮
                if (p.status === 'on_sale') {
                    statusBtn = `<button onclick="updateStatus(${p.id}, 'off_sale')" class="btn warning">下架</button>`;
                } else if (p.status === 'off_sale') {
                    statusBtn = `<button onclick="updateStatus(${p.id}, 'on_sale')" class="btn success">上架</button>`;
                } else if (p.status === 'pending') {
                    // 待审核状态只显示提示，不允许操作
                    statusBtn = `<span class="status-badge pending">等待审核中</span>`;
                }

                // 添加删除按钮
                const deleteBtn = `<button onclick="deleteProduct(${p.id})" class="btn danger">删除</button>`;

                listHtml += `<tr>
                <td>${p.imageUrl ? `<img src="${p.imageUrl}" alt="${p.name}" style="width: 80px; height: 45px; object-fit: cover;">` : '无图片'}</td>
                <td>${p.name || '无名称'}</td>
                <td>¥${p.price || '0'}</td>
                <td>${category}</td>
                <td>${status}</td>
                <td>${createdDate}</td>
                <td>${validUntil}</td>
                <td>${editBtn} ${statusBtn} ${deleteBtn}</td>
            </tr>`;
            }

            listHtml += '</table>';
            document.getElementById('productList').innerHTML = listHtml;

            // 分页
            let paginationHtml = '';
            for (let i = 0; i < data.totalPages; i++) {
                paginationHtml += `<button onclick="page=${i};loadMyProducts()" class="${i === data.number ? 'active' : ''}">${i+1}</button>`;
            }
            document.getElementById('pagination').innerHTML = paginationHtml;

        } catch (e) {
            console.error('加载我的商品失败:', e);
            document.getElementById('productList').innerHTML = '<p class="error-msg">加载商品失败，请刷新页面重试</p>';
        }
    }

    async function updateStatus(productId, status) {
        try {
            const res = await fetch(`/api/products/${productId}/status?status=${status}`, {
                method: 'POST',
                credentials: 'include'
            });

            const data = await res.json();

            if (data.error) {
                document.getElementById('msg').innerHTML = `<p class="error-msg">${data.error}</p>`;
            } else {
                document.getElementById('msg').innerHTML = '<p class="success-msg">商品状态已更新</p>';
                // 重新加载商品列表
                loadMyProducts();
            }
        } catch (e) {
            console.error('更新商品状态失败:', e);
            document.getElementById('msg').innerHTML = '<p class="error-msg">操作失败，请重试</p>';
        }
    }

    async function deleteProduct(productId) {
        if (!confirm('确定要删除这个商品吗？此操作不可恢复！')) {
            return;
        }

        try {
            const res = await fetch(`/api/products/${productId}`, {
                method: 'DELETE',
                credentials: 'include'
            });

            if (!res.ok) {
                throw new Error(`服务器返回错误: ${res.status}`);
            }

            document.getElementById('msg').innerHTML = '<p class="success-msg">商品已删除</p>';
            // 重新加载商品列表
            loadMyProducts();
        } catch (e) {
            console.error('删除商品失败:', e);
            document.getElementById('msg').innerHTML = `<p class="error-msg">删除失败: ${e.message || '未知错误'}</p>`;
        }
    }

    // 页面加载时加载商品
    loadMyProducts();
</script>
<style>
    .controls {
        margin-bottom: 20px;
        text-align: right;
    }

    .empty-state {
        text-align: center;
        padding: 40px 0;
    }

    .empty-state p {
        font-size: 18px;
        margin-bottom: 20px;
        color: var(--text-secondary);
    }

    .warning {
        background-color: var(--warning-color);
    }

    .success {
        background-color: var(--success-color);
    }

    .danger {
        background-color: #dc3545;
        color: white;
    }

    .btn {
        margin-right: 5px;
    }

    .status-badge {
        display: inline-block;
        padding: 5px 10px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
    }

    .status-badge.pending {
        background-color: #f0ad4e;
        color: white;
    }
</style>
</body>
</html> 